<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="物料号" prop="itemCode">
        <el-input
          v-model="queryParams.itemCode"
          placeholder="请输入物料号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物料名称" prop="itemName">
        <el-input
          v-model="queryParams.itemName"
          placeholder="请输入物料名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="标签号" prop="lableCode">
        <el-input
          v-model="queryParams.lableCode"
          placeholder="请输入标签号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="器具位置号" prop="applianceyCode">
        <el-input
          v-model="queryParams.applianceyCode"
          placeholder="请输入器具位置号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="器具名称" prop="applianceyName">
        <el-input
          v-model="queryParams.applianceyName"
          placeholder="请输入器具名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="供应商编号" prop="suppCode">
        <el-input
          v-model="queryParams.suppCode"
          placeholder="请输入供应商编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="供应商名称" prop="suppName">
        <el-input
          v-model="queryParams.suppName"
          placeholder="请输入供应商名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="sps区" prop="spsArea">
        <el-input
          v-model="queryParams.spsArea"
          placeholder="请输入sps区"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线体编号" prop="lineCode">
        <el-input
          v-model="queryParams.lineCode"
          placeholder="请输入线体编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="线体名称" prop="lineName">
        <el-input
          v-model="queryParams.lineName"
          placeholder="请输入线体名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:jciteminfo:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:jciteminfo:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:jciteminfo:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['business:jciteminfo:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="handleImport"
        >导入</el-button>
      </el-col>

      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jciteminfoList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-data"
            @click="handleCode(scope.row)"
          >条码预览</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:jciteminfo:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:jciteminfo:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
      <!--<el-table-column label="主键" align="center" prop="id" />-->
      <el-table-column label="物料号" align="center" prop="itemCode" width="150px"/>
      <el-table-column label="物料名称" align="center" prop="itemName" width="150px" :show-overflow-tooltip="true"/>
      <el-table-column label="标签号" align="center" prop="lableCode" />
      <el-table-column label="器具位置号" align="center" prop="applianceyCode" width="150px"/>
      <el-table-column label="器具编号" align="center" prop="res1"/>
      <el-table-column label="器具名称" align="center" prop="applianceyName" width="150px"/>
      <el-table-column label="补货期量" align="center" prop="qlNum" />
      <el-table-column label="段位" align="center" prop="res2"/>
      <el-table-column label="供应商编号" align="center" prop="suppCode" width="150px"/>
      <el-table-column label="供应商名称" align="center" prop="suppName" width="150px" :show-overflow-tooltip="true"/>
      <el-table-column label="单位" align="center" prop="unit">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.unit" :value="scope.row.unit"/>
        </template>
      </el-table-column>
      <el-table-column label="sps区" align="center" prop="spsArea" />
      <el-table-column label="线体编号" align="center" prop="lineCode" />
      <el-table-column label="线体名称" align="center" prop="lineName" />
     <!-- <el-table-column label="备注" align="center" prop="bz" />
      <el-table-column label="备用1" align="center" prop="res1" />
      <el-table-column label="备用3" align="center" prop="res3" />
      <el-table-column label="备用4" align="center" prop="res4" />-->
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="caeateUser" />

    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="12">
          <el-form-item label="物料号" prop="itemCode">
            <el-input v-model="form.itemCode" placeholder="请输入物料号" :disabled="isUpdate"/>
          </el-form-item>
          </el-col>
          <el-col :span="12">
          <el-form-item label="物料名称" prop="itemName">
            <el-input v-model="form.itemName" placeholder="请输入物料名称" />
          </el-form-item>
          </el-col>
        </el-row>
        <el-row>
        <el-col :span="12">
        <el-form-item label="标签号" prop="lableCode">
          <el-input v-model="form.lableCode" placeholder="请输入标签号" />
        </el-form-item>
        </el-col>
          <el-col :span="12">
        <el-form-item label="器具位置号" prop="applianceyCode">
          <el-input v-model="form.applianceyCode" placeholder="请输入器具位置号" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-row>

          <el-col :span="12">
            <el-form-item label="器具编号" prop="res1">
              <el-input v-model="form.res1"  placeholder="请输入器具编号" />
            </el-form-item>
          </el-col>
            <el-col :span="12">
          <el-form-item label="器具名称" prop="applianceyName">
            <el-input v-model="form.applianceyName" placeholder="请输入器具名称" />
          </el-form-item>
            </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="供应商编号" prop="suppCode">
              <el-input v-model="form.suppCode" placeholder="请输入供应商编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="供应商名称" prop="suppName">
              <el-input v-model="form.suppName" placeholder="请输入供应商名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="单位" prop="unit">
              <el-select v-model="form.unit" placeholder="请选择单位">
                <el-option
                  v-for="dict in dict.type.unit"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
        <el-form-item label="sps区" prop="spsArea">
          <el-input v-model="form.spsArea" placeholder="请输入sps区" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
        <el-form-item label="线体编号" prop="lineCode">
          <el-input v-model="form.lineCode" placeholder="请输入线体编号" />
        </el-form-item>
          </el-col>
          <el-col :span="12">
        <el-form-item label="线体名称" prop="lineName">
          <el-input v-model="form.lineName" placeholder="请输入线体名称" />
        </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="补货期量" prop="qlNum">
              <el-input v-model="form.qlNum"   type="number" placeholder="请输入补货期量" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="段位" prop="res2">
              <el-input v-model="form.res2" placeholder="请输入段位" />
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 物料导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls" :headers="upload.headers" :action="upload.url + '?updateSupport=' + upload.updateSupport" :disabled="upload.isUploading" :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--   <div class="el-upload__tip" slot="tip">
               <el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据
             </div>-->
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link type="primary" :underline="false" style="font-size: 12px; vertical-align: baseline" @click="importTemplate">下载模板</el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>


    <!-- 2025-01-08二维码-->
    <el-dialog :title="titleCode" :visible.sync="openCode" width="700px" append-to-body>

      <div ref="print" id="printMe3">
        <div style="margin-bottom: 30px;">
          <el-row :gutter="5">
            <el-col :span="12" style="padding-left: 90px;margin-top: -10px">
              <h2 style="font-size: 16px;font-weight: bold">物料号:{{item.itemCode}}</h2>
              <h2 style="font-size: 16px;font-weight: bold">物料名称：{{item.itemName}}</h2>
              <h2 style="font-size: 16px;font-weight: bold">标签号：{{item.lableCode}}</h2>
              <h2 style="font-size: 16px;font-weight: bold">供应商编号：{{item.suppCode}}</h2>
              <h2 style="font-size: 16px;font-weight: bold">供应商名称：{{item.suppName}}</h2>
              <h2 style="font-size: 16px;font-weight: bold">sps区：{{item.spsArea}}</h2>
            </el-col>
            <el-col :span="12">
              <div ref="qrcode">
              </div>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer" style="text-align: right;margin-top: 35px">
        <el-button type="primary" v-print="printObj" >打 印</el-button>
        <el-button @click="canceldy">取 消</el-button>
      </div>
    </el-dialog>




  </div>
</template>

<script>
import { listJciteminfo, getJciteminfo, delJciteminfo, addJciteminfo, updateJciteminfo } from "@/api/business/jciteminfo";
import { getToken } from "@/utils/auth";
import print from "vue-print-nb";
import QRCode from 'qrcodejs2';
export default {

  directives: {
    print
  },

  name: "Jciteminfo",
  dicts: ['unit'],
  data() {


    var validateitemCode = (rule, value, callback) => {
      var reg = /^.{0,50}$/;
      if(!reg.test(value) && value!=undefined && value!=""){
        return callback(new Error('物料编号过长!'));
      } else{
        callback();
      }
    };

    var validateupLine = (rule, value, callback) => {
      var reg = /^\+?(0|[1-9][0-9]*)$/
      if(!reg.test(value) && value!=undefined && value!=""){
        return callback(new Error('期量只能是整数!'));
      } else{
        callback();
      }
    };

    return {

      //打印对象
      printObj: {
        id: "printMe3",//必填项，需部分打印输入的ID
        popTitle: "物料二维码",//标题显示标题
        extraCss: "",//附加链接连接，以逗号分隔
        extraHead: '<meta http-equiv="Content-Language"content="zh-cn"/>',//附加到head标签的附加标签，以逗号分隔
      },
      isUpdate:false,

      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料信息表格数据
      jciteminfoList: [],
      // 弹出层标题
      title: "",
      //二维码弹窗标题
      titleCode:"",
      // 是否显示弹出层
      open: false,
      //二维码弹窗
      openCode:false,

      currentDate:null,

      //物料对象
      item:{},

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        itemCode: null,
        itemName: null,
        lableCode: null,
        applianceyCode: null,
        applianceyName: null,
        qlNum: null,
        suppCode: null,
        suppName: null,
        unit: null,
        spsArea: null,
        lineCode: null,
        lineName: null,
        bz: null,
        res1: null,
        res2: null,
        res3: null,
        res4: null,
        caeateUser: null
      },
      // 表单参数
      form: {},

      // 物料导入参数
      upload: {
        // 是否显示弹出层（物料导入）
        open: false,
        // 弹出层标题（物料导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的物料数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/business/jciteminfo/importData"
      },

      // 表单校验
      rules: {
        itemCode: [
          { required: true, message: "物料编号不能为空", trigger: "blur" },
          { validator: validateitemCode,trigger: "blur" }
        ],

        itemName: [
          { required: true, message: "物料名称不能为空", trigger: "blur" },
          { validator: validateitemCode,trigger: "blur" }
        ],

        qlNum: [
          { required: true, message: "期量不能为空", trigger: "blur" },
          { validator: validateupLine,trigger: "blur" }
        ],

        lableCode: [
          { required: true, message: "标签号不能为空", trigger: "blur" },
        ],




      }
    };
  },
  created() {
    this.getList();
  },
  methods: {

    cshDate(){
      // 获取当前时间
      var now = new Date();

// 格式化为指定格式（例如：YYYY-MM-DD HH:MM:SS）
      var formattedDateTime = now.getFullYear() + '-' +
        ('0' + (now.getMonth() + 1)).slice(-2) + '-' +
        ('0' + now.getDate()).slice(-2) + ' ' +
        ('0' + now.getHours()).slice(-2) + ':' +
        ('0' + now.getMinutes()).slice(-2) + ':' +
        ('0' + now.getSeconds()).slice(-2);

      console.log(formattedDateTime); // 输出格式化后的时间
      this.currentDate = formattedDateTime;

    },
    /** 条码预览操作 */
    handleCode(row) {
    this.item = row;
    this.titleCode ="条码预览";
    this.openCode = true;
      this.$nextTick(() => {
        this.generateQRCode();
      });
    },


    generateQRCode() {
      const div = this.$refs.qrcode; // 获取对应的 div 元素
      div.innerHTML = ''; // 清空 div 内容

      const text = this.item.lableCode;
      // 使用 QRCode 实例生成二维码
      new QRCode(div, {
        width: 160,
        height: 150,
        text: text
      });
    },

    canceldy(){
      this.text = "";
      this.openCode = false;
    },


    /** 查询物料信息列表 */
    getList() {
      this.loading = true;
      listJciteminfo(this.queryParams).then(response => {
        this.jciteminfoList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        itemCode: null,
        itemName: null,
        lableCode: null,
        applianceyCode: null,
        applianceyName: null,
        qlNum: null,
        suppCode: null,
        suppName: null,
        unit: null,
        spsArea: null,
        lineCode: null,
        lineName: null,
        bz: null,
        res1: null,
        res2: null,
        res3: null,
        res4: null,
        createTime: null,
        caeateUser: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.isUpdate  = false;
      this.reset();
      this.open = true;
      this.title = "添加物料信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.isUpdate  = true;
      this.reset();
      const id = row.id || this.ids
      getJciteminfo(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改物料信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateJciteminfo(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addJciteminfo(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除物料信息编号为"' + ids + '"的数据项？').then(function() {
        return delJciteminfo(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },

    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "物料导入";
      this.upload.open = true;
    },

    /** 下载模板操作 */
    importTemplate() {
      this.download('business/jciteminfo/importTemplate', {
      }, `物料导入_${new Date().getTime()}.xlsx`)
    },

    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "导入结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },



    /** 导出按钮操作 */
    handleExport() {
      this.download('business/jciteminfo/export', {
        ...this.queryParams
      }, `jciteminfo_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
